import Taro from "@tarojs/taro";
import config from '@/app.config';
import message from './message';
import models from "@/models";
import { createCustomError } from "./error";

const LOGIN_PAGE = '/pages/login/index';

type IGoLoginOptions = {
  /** 是否自动登录 */
  autoLogin?: boolean;
  /** 是否清除抖音授权内容 */
  cleanLogined?: boolean;
};

/**
 * 跳转登录页面
 * @param
 */
export function goLogin(options?: IGoLoginOptions) {
  if (options?.autoLogin !== undefined) {
    models.user.setCanAutoLogin(true);
  }

  if (options?.cleanLogined) {
    models.user.cleanLogined();
  }

  goToPage(LOGIN_PAGE, {
    method: 'reLaunch',
  });
}

/**
 * 获取当前路由路径
 * @returns
 */
export function getCurrentPath() {
  return Taro.getCurrentInstance().router?.path ?? '';
}

type IGoToPageOptions = {
  method?: 'navigateTo' | 'redirectTo' | 'reLaunch';
  params?: object;
};
export function convertParams2QueryString(params?: object) {
  if (!params) {
    return '';
  }

  return Object.keys(params)
    .reduce((p, k) => {
      const t = params[k];

      // 过滤空值
      if (![undefined, null, ''].includes(t)) {
        p.append(k, typeof t === 'object' ? JSON.stringify(t) : t);
      }

      return p;
    }, new URLSearchParams())
    .toString();
}
export function resolvePageUrlWithParams(page: string, params?: object) {
  let url = page;

  const query = convertParams2QueryString(params);
  if (query) {
    url = `${url}?${query}`;
  }

  return url;
}
/**
 * 通用页面跳转方法
 * @param page 页面地址
 * @param options 配置信息
 */
export function goToPage(page: string, options?: IGoToPageOptions) {
  const { method = 'navigateTo', params = {} } = options ?? {};

  const tabPages = (config.tabBar?.list ?? []).map(d => d.pagePath);

  const url = resolvePageUrlWithParams(page, params);

  if (tabPages.find(d => d.includes(page) || page.includes(d))) {
    Taro[method === 'reLaunch' ? 'reLaunch' : 'switchTab']({
      url,
    });
  } else {
    Taro[method]({
      url,
    });
  }
}

/**
 * 判断路径是否不相同
 * @param path 目标路径
 * @returns
 */
export function isDiffWithCurrent(path: string) {
  return getCurrentPath() !== path;
}

export enum EUserErrorType {
  /** 未知错误 */
  unknown = 0,
  /** 账号未登录 */
  no_login = 1,
  /** 账号未授权 */
  no_valid = 401,
  /** 账号未注册 */
  no_verify = 491
}

/**
* 创建用户路由错误
* @param message 错误信息
* @param errorType 错误类型
* @returns
*/
export function createUserRouterError(msg: string, errorType: EUserErrorType) {
  return createCustomError(msg, errorType);
}

/**
 * 处理用户路由错误
 * @param error 路由错误
 */
export function handleUserRouterError(routerError: any) {
  const routes = {
    [EUserErrorType.no_login]: LOGIN_PAGE,
    [EUserErrorType.no_verify]: '/pages/noverify/index'
  };
  console.log('错误路由', routerError)

  switch (routerError?.payload) {
    case EUserErrorType.no_login:
      isDiffWithCurrent(routes[EUserErrorType.no_login]) && goLogin();
      break;
    case EUserErrorType.no_verify:
      isDiffWithCurrent(routes[EUserErrorType.no_verify]) &&
        goToPage(routes[EUserErrorType.no_verify], {
          method: 'reLaunch',
        });
      break;
    default:
      message.error(routerError?.message, 1500).then(() => {
        isDiffWithCurrent(routes[EUserErrorType.no_login]) && goLogin();
      });
      break;
  }
}